package server;
import java.util.HashMap;
import java.util.UUID;

public class Server implements ServerInterface{
	
	HashMap <Integer, Session> activeSessions;
	private final int maxConnections = 10;
	private Database database;
	
	public Server () {
		this.database = new Database();
	}
	
	public Session login(int userID, String pass) {
		if (!this.validPassword(userID, pass)) {
			return new Session(0, null,"Wrong Password");
		}
		if (this.activeSessions.containsKey(userID)) {
			return activeSessions.get(userID);
		}
		if (this.activeSessions.size() >= this.maxConnections) {
			return new Session(0, null,"Too many connections");
		}
		Session session = new Session(userID, generateSessionID(userID), "Login success");
		this.activeSessions.put(userID, session);
		return session;
	}
	
	public void logout(int userID, String sessionID) {
		if (this.validSession(userID, sessionID)) {
			this.activeSessions.remove(userID);
		}
	}
	
	private String generateSessionID(int userID) {
		return Integer.toString(userID)+UUID.randomUUID();
	}

	private boolean validSession(int userID, String sessionID) {
		if (this.activeSessions.containsKey(userID)) {
			if (this.activeSessions.get(userID).getsessionID() == sessionID) {
				return true;
			}
		}
		return false;
	}
	
	private boolean validPassword(int userID, String pass) {
		User user = this.database.select(userID);
		if (user.getpass() == pass) {
			return true;
		}
		return false;
	}

	public boolean changePassword(int userID, String sessionID, String oldpass, String newpass) {
		if (this.validSession(userID, sessionID)) {
			if (this.validPassword(userID, oldpass)) {
				User user = this.database.select(userID);
				if (user != null) {
					return this.database.update(userID, user.getoprNavn(), user.getcpr(), newpass, user.getini());
				}
			}
		}
		return false;
	}

	

	public boolean addUser() {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean deleteUser() {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean editUser() {
		// TODO Auto-generated method stub
		return false;
	}

	public String[] showUsers() {
		// TODO Auto-generated method stub
		return null;
	}
}
